'''
昆仑健康保重大疾病保险（2.0版）
'''
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests, json
from common.helper import Helper
from threading import Thread
from pprint import pprint


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "昆仑健康保重大疾病保险（2.0版）"

    # 生成产品数据
    def genProductInfo(self):

        plan = {

            "planA": {
                # 0 - 40
                "year": [str(i) for i in range(0, 41)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险金额
                "money": ["200000", "300000", "400000", "500000", "600000"],
                # 保险期间
                "expire": ["80岁", "终身"],
                # 缴费间隔
                "interval": ["0", "5", "10", "15", "20", "30"],
                # 身故、全残及疾病终末期保险金
                "death": ["'" + json.dumps({"dutyCode": "516006", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                          '0'],
                # 恶性肿瘤保险金
                "cancer": ["'" + json.dumps({"dutyCode": "516005", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                           '0'],
                # 重大疾病医疗津贴保险金
                "serious": ["'" + json.dumps({"dutyCode": "516004", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                            '0'],
                # 成人特定疾病保险金
                "adult": ["'" + json.dumps({"dutyCode": "516003", "dutyAmnt": "300000"}, ensure_ascii=False) + "'", '0']

            },
            "planB": {
                # 41 - 45
                "year": [str(i) for i in range(41, 46)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险金额
                "money": ["200000", "300000", "400000", "500000"],
                # 保险期间
                "expire": ["80岁", "终身"],
                # 缴费间隔
                "interval": ["0", "5", "10", "15", "20"],
                # 身故、全残及疾病终末期保险金
                "death": ["'" + json.dumps({"dutyCode": "516006", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                          '0'],
                # 恶性肿瘤保险金
                "cancer": ["'" + json.dumps({"dutyCode": "516005", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                           '0'],
                # 重大疾病医疗津贴保险金
                "serious": ["'" + json.dumps({"dutyCode": "516004", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                            '0'],
                # 成人特定疾病保险金
                "adult": ["'" + json.dumps({"dutyCode": "516003", "dutyAmnt": "300000"}, ensure_ascii=False) + "'", '0']

            },
            "planC": {
                # 46 - 50
                "year": [str(i) for i in range(46, 51)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险金额
                "money": ["100000", "200000", "300000"],
                # 保险期间
                "expire": ["80岁", "终身"],
                # 缴费间隔
                "interval": ["0", "5", "10", "15"],
                # 身故、全残及疾病终末期保险金
                "death": ["'" + json.dumps({"dutyCode": "516006", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                          '0'],
                # 恶性肿瘤保险金
                "cancer": ["'" + json.dumps({"dutyCode": "516005", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                           '0'],
                # 重大疾病医疗津贴保险金
                "serious": ["'" + json.dumps({"dutyCode": "516004", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                            '0'],
                # 成人特定疾病保险金
                "adult": ["'" + json.dumps({"dutyCode": "516003", "dutyAmnt": "300000"}, ensure_ascii=False) + "'", '0']

            },
            "planD": {
                # 51- 55
                "year": [str(i) for i in range(51, 56)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险金额
                "money": ["100000", "200000"],
                # 保险期间
                "expire": ["80岁", "终身"],
                # 缴费间隔
                "interval": ["0", "5", "10"],
                # 身故、全残及疾病终末期保险金
                "death": ["'" + json.dumps({"dutyCode": "516006", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                          '0'],
                # 恶性肿瘤保险金
                "cancer": ["'" + json.dumps({"dutyCode": "516005", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                           '0'],
                # 重大疾病医疗津贴保险金
                "serious": ["'" + json.dumps({"dutyCode": "516004", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                            '0'],
                # 成人特定疾病保险金
                "adult": ["'" + json.dumps({"dutyCode": "516003", "dutyAmnt": "300000"}, ensure_ascii=False) + "'", '0']

            },
            "planE": {
                # 51- 45
                "year": [str(i) for i in range(56, 61)],
                # 性别 0 男 1 女
                "gender": ["0", "1"],
                # 保险金额
                "money": ["100000", "200000"],
                # 保险期间
                "expire": ["80岁", "终身"],
                # 缴费间隔
                "interval": ["0", "5"],
                # 身故、全残及疾病终末期保险金
                "death": ["'" + json.dumps({"dutyCode": "516006", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                          '0'],
                # 恶性肿瘤保险金
                "cancer": ["'" + json.dumps({"dutyCode": "516005", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                           '0'],
                # 重大疾病医疗津贴保险金
                "serious": ["'" + json.dumps({"dutyCode": "516004", "dutyAmnt": "300000"}, ensure_ascii=False) + "'",
                            '0'],
                # 成人特定疾病保险金
                "adult": ["'" + json.dumps({"dutyCode": "516003", "dutyAmnt": "300000"}, ensure_ascii=False) + "'", '0']

            },

        }

        for k in plan:

            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["expire"],
                             plan[k]["interval"], plan[k]["death"], plan[k]["cancer"], plan[k]["serious"],
                             plan[k]["adult"]):
                # SQL = domain[self.name]["insert_sql"].format(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7],v[8])

                SQL = 'INSERT INTO `昆仑健康保重大疾病保险（2.0版）`(`year`,`gender`,`money`,`expire`,`interval`,`death`,`cancer`,`serious`,`adult`)VALUES("{0}","{1}","{2}","{3}","{4}",{5},{6},{7},{8})'

                data = SQL.format(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8])

                self.mysql.cursor.execute(data)

                self.mysql._conn.commit()

                print(data)

    # 执行爬虫
    def requestJson(self,dt=None,mysql=None):

        #
        # dt = {
        #
        #     "year":"1",
        #     "gender":"0",
        #     "money":"300000",
        #     "expire":"80岁",
        #     "interval":"20",
        #     "death":"0",
        #     "cancer":"1",
        #     "serious":"0",
        #     "adult":"1"
        # }

        money = dt["money"]

        dy = {

            "death":dt["death"],
            "cancer":dt["cancer"],
            "serious":dt["serious"],
            "adult":dt["adult"]
        }

        code = {

            "death":'{"dutyCode":"516006","dutyAmnt":"'+money+'"}]}',
            "cancer":'{"dutyCode":"516005","dutyAmnt":"'+money+'"}',
            "serious":'{"dutyCode":"516004","dutyAmnt":"'+money+'"}',
            "adult":'{"dutyCode":"516003","dutyAmnt":"'+money+'"}'
        }

        string = ''

        for k,v in dy.items():

            if v!="0":

                dd = code[k]

                string += "," + dd

            else:

                pass

        if dt["interval"] != "0":

            strList = '[{"dutyCode": "516001", "dutyAmnt": "'+money+'"}' + string +',{"dutyCode":"516007","dutyAmnt":"'+money+'"}'+ "]"

        else:

            strList = '[{"dutyCode": "516001", "dutyAmnt": "' + money + '"}' + string +"]"


        data = {

            "insuredsStr": '[{"birthday": "'+str( 2019-int(dt["year"]))+'-06-07", "sex": "'+dt["gender"]+'", "planInfos": [{"riskCode": "I161", "mainRiskCode": "I161", "planCode": "33", "planPeriod": "'+dt["expire"]+'", "payType": "0","payEndYearFlag":"", "payEndYear":"'+dt["interval"]+'", "dutys": '+strList+'}]}]'

        }

        payload = urlencode(data).replace("+", '') + "&isOrder=0&productID=37"

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

        pprint( r.text )
        if r.status_code == 200 and  '保费计算_[0]被保人_被保险人及险种信息校验_险种代码不能为空!' not in r.text:

            price = Helper.decimalParse(r.json()["data"]["data"]["premiun"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            mysql.updatePrice( data )

        else:

            # 任务执行失败
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("产品价格更新失败:", dt["id"])


    def main(self, mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt, mysql)

    def startProcess(self):

        threads = []

        for i in range(5):
            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()

            threads.append(t)

        for t in threads:
            t.join()
